package com.njym.java.security.app.rest;


import com.njym.java.security.app.biz.UserRelationBiz;
import com.njym.java.security.app.entity.FamilyUser;
import com.njym.java.security.app.entity.UserMessage;
import com.njym.java.security.app.entity.UserRelation;
import com.njym.java.security.app.entity.UserRelationVo;
import com.njym.java.security.common.msg.ObjectRestResponse;
import com.njym.java.security.common.rest.BaseController;
import com.njym.java.security.common.util.ResponseUtil;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("userRelation")
public class UserRelationController extends BaseController<UserRelationBiz,UserRelation> {
    private final Log logger = LogFactory.getLog(UserRelationController.class);
    @Autowired
    private PlatformTransactionManager txManager;

    /**
     * 查询好友
     * @param userId
     * @return
     */
    @RequestMapping(value = "/queryFriend",method = RequestMethod.GET)
    @ResponseBody
    public Object queryFriend(String userId){
        if (!userId.equals("undefined")) {
            Example example = new Example(UserRelation.class);
            example.createCriteria().andEqualTo("userId", Integer.parseInt(userId)).andEqualTo("relation", 1);
            List<UserRelation> list = baseBiz.selectByExample(example);
            Map<String, Object> data = new HashMap<>(2);
            data.put("list", list);
            return new ObjectRestResponse<UserMessage>().rel(true).data(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }


    }

    /**
     * 查询好友申请
     * @param userId
     * @return
     */
    @RequestMapping(value = "/queryFriendApply",method = RequestMethod.GET)
    @ResponseBody
    public Object queryFriendApply(String userId){
        if (!userId.equals("undefined")) {
            List<UserRelationVo> list = baseBiz.queryFriendApply(Integer.parseInt(userId));
            Map<String, Object> data = new HashMap<>(1);
            data.put("list", list);
            return new ObjectRestResponse<UserMessage>().rel(true).data(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }

    }

    @RequestMapping(value = "/queryUser",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUser> queryUser(String mobile){

        List<FamilyUser> list = baseBiz.queryUser(mobile);
        Map<String, Object> data = new HashMap<>(1);

        data.put("list", list);
        return new ObjectRestResponse<FamilyUser>().rel(true).data(data);

    }


    @RequestMapping(value = "/addFriend",method = RequestMethod.GET)
    @ResponseBody
    public Object addFriend(String userId, String friendId,
        String friendName, String avatar, String attr2){
        if (!userId.equals("undefined") && !friendId.equals("undefined")) {
            List<UserRelation> relation = baseBiz.checkFriend(Integer.parseInt(userId), Integer.parseInt(friendId));
            if(relation.size() > 0){
                return new ObjectRestResponse<UserRelation>().rel(true).data("no");
            }else {
                UserRelation userRelation = new UserRelation();
                userRelation.setUserId(Integer.parseInt(userId));
                userRelation.setFriendId(Integer.parseInt(friendId));
                userRelation.setFriendName(friendName);
                userRelation.setAvatar(avatar);
                userRelation.setAttr2(attr2);
                userRelation.setAttr3(getPinYinHeadChar(friendName).toUpperCase());
                userRelation.setRelation(0);
                baseBiz.insertSelective(userRelation);
                Map<String, Object> data = new HashMap<>(1);

                return new ObjectRestResponse<UserRelation>().rel(true).data(data);
            }
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }

    }

    /**
     * 同意好友
     * @param userId
     * @param friendId
     * @param friendName
     * @param avatar
     * @param attr2
     * @return
     */
    @RequestMapping(value = "/acceptFriend",method = RequestMethod.GET)
    @ResponseBody
    public Object acceptFriend(String userId, String friendId,
        String friendName, String avatar, String attr2){
        if (!userId.equals("undefined") && !friendId.equals("undefined")) {
            UserRelation userRelation = new UserRelation();
            userRelation.setUserId(Integer.parseInt(userId));
            userRelation.setFriendId(Integer.parseInt(friendId));
            userRelation.setFriendName(friendName);
            userRelation.setAvatar(avatar);
            userRelation.setAttr2(attr2);
            userRelation.setAttr3(getPinYinHeadChar(friendName).toUpperCase());
            userRelation.setRelation(1);

            // 开启事务管理
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            TransactionStatus status = txManager.getTransaction(def);
            try {
                baseBiz.insertSelective(userRelation);

                baseBiz.updateRelation(Integer.parseInt(friendId), Integer.parseInt(userId));
            }catch (Exception ex) {
                txManager.rollback(status);
                logger.error("网络连接超时", ex);
            }
            txManager.commit(status);


            Map<String, Object> data = new HashMap<>(1);

            return new ObjectRestResponse<UserRelation>().rel(true).data(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }

    }

    /**
     * 拒绝好友
     * @param userId
     * @param friendId
     * @return
     */
    @RequestMapping(value = "/rejectFriend",method = RequestMethod.GET)
    @ResponseBody
    public Object rejectFriend(String userId, String friendId){
        if (!userId.equals("undefined") && !friendId.equals("undefined")) {
            baseBiz.rejectFriend(Integer.parseInt(friendId), Integer.parseInt(userId));
            Map<String, Object> data = new HashMap<>(1);
            return new ObjectRestResponse<UserRelation>().rel(true).data(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }

    }

    /**
     * 中文转首字符
     * @param str
     * @return
     */
    public static String getPinYinHeadChar(String str) {
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }
}

